/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-06-24
 * Time: 23:19
 */
//力扣：https://leetcode.cn/problems/linked-list-cycle/submissions/638974266/
    //给你一个链表的头节点 head ，判断链表中是否有环。
class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }
public class Test {
    public static boolean hasCycle(ListNode head) {
        ListNode p1=head;
        ListNode p2=head;
        while(p2!=null&&p2.next!=null){
            p2=p2.next.next;
            p1=p1.next;
            if(p1==p2){
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        ListNode list1=new ListNode(1);
        ListNode list2=new ListNode(2);
        ListNode list3=new ListNode(3);
        ListNode list4=new ListNode(4);
        ListNode list5=new ListNode(5);
        list1.next=list2;
        list2.next=list3;
        list3.next=list4;
        list4.next=list5;
        System.out.println(hasCycle(list1));
        list5.next=list3;
        System.out.println(hasCycle(list1));
    }
}
